package com.yuan;

import java.util.Arrays;

/**
 * @ClassName: string
 * @Description: TODO
 * @Author MrYuan
 * @Date: 2021/3/2 12:14
 * @Version 1.0
 */
public class ytrings {
    public static void main(String[] args) {
        String s1 = "gbcebacd";
        String s2 = "bacd";
        String st3 = "aaab";
//        System.out.println(match(s1, s2));
//        System.out.println(Arrays.toString(kmpNext(st3)));
        int[] next = kmpNext(s2);
        System.out.println(kmpsearching(s1, s2, next));
    }
    public static int match(String st1, String st2) {
        int s1 = st1.length();
        int s2 = st2.length();
        int i = 0;
        int j = 0;
        while (i < s1 && j < s2) {
            if (st1.charAt(i) == st2.charAt(j)) {
                i++;
                j++;
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }
        if (j == s2) {
            return s1 - j;
        } else {
            return -1;
        }
    }

    public static int kmpsearching(String str1, String str2, int[] next) {

        for (int i = 0, j = 0; i < str1.length(); i++) {
           while (j>0&&str1.charAt(i)!=str2.charAt(j)){
               j=next[j-1];
           }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }

        return -1;
    }

    public static int[] kmpNext(String str) {
        int[] next = new int[str.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < str.length(); i++) {
            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j = next[j - 1];
            }
            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}